"""excel格式的测试用例处理"""
import csv

import allure
import pandas
from openpyxl.reader.excel import load_workbook
from config.config import *
from utils.dict_utils import dict_nan_to_none
from utils.exception_utils import ExcelException
from utils.timestamp_utils import *
from utils.verify_utils import get_captcha_code
from utils.logger_utils import *

def get_excel_data(testcase_excel=TESTCASE_EXCEL,testcase_sheet=TESTCASE_SHEET):
    testcase_list = []
    try:
        pd = pandas.read_excel(testcase_excel,testcase_sheet,skiprows=SKIP_ROWS)
        for k,v in pd.iterrows():
            #剔除为nan的数据
            testcase_dict = dict_nan_to_none(v.to_dict())
            testcase_list.append(testcase_dict)
        info(f"testcase_list={testcase_list}")
        return testcase_list
    except Exception as e:
        info(f"pandas读取测试用例错误！{e}")
        raise ExcelException


@allure.step("1、分拣请求参数")
def excel_to_req(dictname):
    try:
        #info(f"传入={dictname}")
        req = {
            "method":dictname["method"],
            "url":API_URL+dictname["url"],
            "params":eval(dictname["params"]) if dictname["params"] else None,
            "data":eval(dictname["data"]) if dictname["data"] else None,
            "json":eval(dictname["json"]) if dictname["json"] else None,
            "headers":eval(dictname["headers"]) if dictname["headers"] else None
        }
        #info(f"分拣后参数={req}")
        allure.attach(f"{req}",name="分拣后参数")
        return req
    except Exception as e:
        info(f"excel请求参数异常！{e}")
        raise ExcelException

def excel_to_exp(dictname):
    try:
        exp = {
            "expect": dictname["expect"] if pandas.notna(dictname["expect"]) else None
        }
        return exp
    except Exception as e:
        info(f"excel提取参数异常！{e}")
        raise ExcelException


def slowApiCsv(param,r,path):
    """
    慢接口的信息写入到一个csv中
    :param param: 测试用例对象
    :param r: request返回对象
    :param path: csv路径
    :return:
    """

    row_data = [param["title"],r.elapsed.total_seconds()]

    with open(path,"w",encoding="utf-8") as file:
        writer = csv.writer(file)
        writer.writerows(row_data)